package com.project.web.order.service.impl.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.project.common.core.utils.exception.CustomException;
import com.project.common.core.utils.exception.RESP_CODE_ENUM;
import com.project.common.core.utils.exception.Result;
import com.project.common.core.utils.id.OrderNoWorker;
import com.project.common.core.utils.weChat.WeChatPayUtil;
import com.project.feign.client.SystemServiceClient;
import com.project.feign.vo.CrmUserInfoVO;
import com.project.web.course.service.impl.common.BaseServiceImpl;
import com.project.web.order.mapper.app.MbrH5OrderMapper;
import com.project.web.order.model.app.MbrH5Order;
import com.project.web.order.service.app.MbrH5OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 * 会员H5订单业务实现类
 *
 * @Author: wyy
 * @Date: 2020-04-08 00:20
 */
@Service("mbrH5OrderServiceImpl")
public class MbrH5OrderServiceImpl extends BaseServiceImpl<MbrH5Order, Long> implements MbrH5OrderService {

    /**
     * 日志工具类
     */
    public static final Logger log = LoggerFactory.getLogger(MbrH5OrderServiceImpl.class);

    @Autowired
    private MbrH5OrderMapper mbrH5OrderMapper;

    @Autowired
    private SystemServiceClient systemServiceClient;

    /**
     * 微信公众号支付统一下单业务【直播0.1元购】
     *
     * @param mbrH5Order 会员H5订单对象
     * @param request    请求对象request
     * @return
     */
    @Transactional
    @Override
    public Map<String, Object> handleunifiedOrder(MbrH5Order mbrH5Order, HttpServletRequest request) {

        // 保存订单数据
        mbrH5Order.setOrderNo(OrderNoWorker.get());
        mbrH5Order.setOrderStatus(MbrH5Order.ORDER_STATUS_ENUM.PRE_PAY.getValue());
        save(mbrH5Order);

        // 封装自定义参数到微信支付订单中
        CrmUserInfoVO crmUserInfoVo = new CrmUserInfoVO();
        crmUserInfoVo.setChannel(MbrH5Order.ORDER_CHANNEL_ENUM.ZB_LDY.getName(mbrH5Order.getOrderChannel()));
        crmUserInfoVo.setPayUserName(mbrH5Order.getPayUserName());
        crmUserInfoVo.setPayUserPhone(mbrH5Order.getPayUserPhone());
        crmUserInfoVo.setScId(mbrH5Order.getScId());
        String crmUserInfoJson = JSON.toJSONString(crmUserInfoVo);

        // 微信小程序支付预下单
        Map<String, Object> returnMap = WeChatPayUtil.unifiedOrderOfPublicNumber(mbrH5Order.getOrderNo(), mbrH5Order.getPayRealAmt(),
                mbrH5Order.getXyMpOpenid(),
                "/order/anon/weChatNotify/H5_PRIME_ORDER",
                "直播1元购",
                crmUserInfoJson,
                request);

        return returnMap;
    }

    /**
     * 微信公众号支付统一下单业务【直播6.6元购】
     *
     * @param mbrH5Order 会员H5订单对象
     * @param request    请求对象request
     * @return
     */
    @Transactional
    @Override
    public Map<String, Object> handleunifiedOrderOfLdl(MbrH5Order mbrH5Order, HttpServletRequest request) {

        // 保存订单数据
        mbrH5Order.setOrderNo(OrderNoWorker.get());
        mbrH5Order.setOrderStatus(MbrH5Order.ORDER_STATUS_ENUM.PRE_PAY.getValue());
        save(mbrH5Order);

        // 封装自定义参数到微信支付订单中
        CrmUserInfoVO crmUserInfoVo = new CrmUserInfoVO();
        crmUserInfoVo.setChannel(MbrH5Order.ORDER_CHANNEL_ENUM.ZB_LDL.getName(mbrH5Order.getOrderChannel()));
        crmUserInfoVo.setPayUserName(mbrH5Order.getPayUserName());
        crmUserInfoVo.setPayUserPhone(mbrH5Order.getPayUserPhone());
        crmUserInfoVo.setScId(mbrH5Order.getScId());
        String crmUserInfoJson = JSON.toJSONString(crmUserInfoVo);

        // 微信小程序支付预下单
        Map<String, Object> returnMap = WeChatPayUtil.unifiedOrderOfPublicNumber(mbrH5Order.getOrderNo(), mbrH5Order.getPayRealAmt(),
                mbrH5Order.getXyMpOpenid(),
                "/order/anon/weChatNotify/H5_PRIME_LDL_ORDER",
                "直播6.6元购",
                crmUserInfoJson,
                request);

        return returnMap;
    }

    /**
     * 微信公众号支付统一下单业务【公众号0.1元购】
     *
     * @param mbrH5Order 会员H5订单对象
     * @param request    请求对象request
     * @return
     */
    @Transactional
    @Override
    public Map<String, Object> unifiedOrderOfMpLdy(MbrH5Order mbrH5Order, HttpServletRequest request) {

        // 保存订单数据
        mbrH5Order.setOrderNo(OrderNoWorker.get());
        mbrH5Order.setOrderStatus(MbrH5Order.ORDER_STATUS_ENUM.PRE_PAY.getValue());
        save(mbrH5Order);

        // 封装自定义参数到微信支付订单中
        CrmUserInfoVO crmUserInfoVo = new CrmUserInfoVO();
        crmUserInfoVo.setChannel(MbrH5Order.ORDER_CHANNEL_ENUM.MP_LDY.getName(mbrH5Order.getOrderChannel()));
        crmUserInfoVo.setPayUserName(mbrH5Order.getPayUserName());
        crmUserInfoVo.setPayUserPhone(mbrH5Order.getPayUserPhone());
        crmUserInfoVo.setScId(null);
        String crmUserInfoJson = JSON.toJSONString(crmUserInfoVo);

        // 微信小程序支付预下单
        Map<String, Object> returnMap = WeChatPayUtil.unifiedOrderOfPublicNumber(mbrH5Order.getOrderNo(), mbrH5Order.getPayRealAmt(),
                mbrH5Order.getXyMpOpenid(),
                "/order/anon/weChatNotify/H5_PRIME_MP_LDY_ORDER",
                "公众号1元购",
                crmUserInfoJson,
                request);

        return returnMap;
    }

    /**
     * 微信公众号支付统一下单业务【公众号0.1元购】
     *
     * @param mbrH5Order 会员H5订单对象
     * @param request    请求对象request
     * @return
     */
    @Transactional
    @Override
    public Map<String, Object> unifiedOrderOfTfYyg(MbrH5Order mbrH5Order, HttpServletRequest request) {

        // 保存订单数据
        mbrH5Order.setOrderNo(OrderNoWorker.get());
        mbrH5Order.setOrderStatus(MbrH5Order.ORDER_STATUS_ENUM.PRE_PAY.getValue());
        save(mbrH5Order);

        // 封装自定义参数到微信支付订单中
        CrmUserInfoVO crmUserInfoVo = new CrmUserInfoVO();
        crmUserInfoVo.setChannel(MbrH5Order.ORDER_CHANNEL_ENUM.TF_YYG.getName(mbrH5Order.getOrderChannel()));
        crmUserInfoVo.setPayUserName(mbrH5Order.getPayUserName());
        crmUserInfoVo.setPayUserPhone(mbrH5Order.getPayUserPhone());
        crmUserInfoVo.setScId(mbrH5Order.getScId());
        String crmUserInfoJson = JSON.toJSONString(crmUserInfoVo);

        // 微信小程序支付预下单
        Map<String, Object> returnMap = WeChatPayUtil.unifiedOrderOfPublicNumber(mbrH5Order.getOrderNo(), mbrH5Order.getPayRealAmt(),
                mbrH5Order.getXyMpOpenid(),
                "/order/anon/weChatNotify/TF_YYG_ORDER",
                "投放1元购",
                crmUserInfoJson,
                request);

        return returnMap;
    }

    /**
     * 微信公众号支付统一下单业务【社团派】
     *
     * @param mbrH5Order 会员H5订单对象
     * @param request    请求对象request
     * @return
     */
    @Transactional
    @Override
    public Map<String, Object> unifiedOrderOfSTP(MbrH5Order mbrH5Order, HttpServletRequest request) {

        // 保存订单数据
        mbrH5Order.setOrderNo(OrderNoWorker.get());
        mbrH5Order.setOrderStatus(MbrH5Order.ORDER_STATUS_ENUM.PRE_PAY.getValue());
        save(mbrH5Order);

        // 封装自定义参数到微信支付订单中
        CrmUserInfoVO crmUserInfoVo = new CrmUserInfoVO();
        crmUserInfoVo.setChannel(mbrH5Order.getChannelName());
        crmUserInfoVo.setPayUserName(mbrH5Order.getPayUserName());
        crmUserInfoVo.setPayUserPhone(mbrH5Order.getPayUserPhone());
        crmUserInfoVo.setScId(null);
        String crmUserInfoJson = JSON.toJSONString(crmUserInfoVo);

        // 微信小程序支付预下单
        Map<String, Object> returnMap = WeChatPayUtil.unifiedOrderOfPublicNumber(mbrH5Order.getOrderNo(), mbrH5Order.getPayRealAmt(),
                mbrH5Order.getXyMpOpenid(),
                "/order/anon/weChatNotify/H5_PRIME_COMMON_LDY_ORDER",
                "社团派0.1",
                crmUserInfoJson,
                request);

        return returnMap;
    }

    /**
     * 处理prime订单异步通知
     *
     * @param outTradeNo    商户单号
     * @param transactionId 交易单号
     * @param payDate       支付时间
     * @param attach        订单自定义参数
     */
    @Transactional
    @Override
    public void handleNotifyOfPrimeOrder(String outTradeNo, String transactionId, Date payDate, String attach) {
        log.info("\r\n****************orderNo={}\r\ntransactionId={}\r\nattach={}", outTradeNo, transactionId, attach);
        // 查询订单
        MbrH5Order mbrH5Order = mbrH5OrderMapper.getByOrderNo(outTradeNo);
        if (mbrH5Order == null) {
            throw new CustomException(RESP_CODE_ENUM.NO_DATA);
        }

        // 判断订单状态是否未未支付状态
        Integer orderStatus = mbrH5Order.getOrderStatus();
        if (!orderStatus.equals(MbrH5Order.ORDER_STATUS_ENUM.PRE_PAY.getValue())) {
            return;
        }

        // 更新订单状态订单数据
        mbrH5Order.setTransactionNo(transactionId);
        mbrH5Order.setPayDate(payDate);
        mbrH5Order.setOrderStatus(MbrH5Order.ORDER_STATUS_ENUM.SUCCESS_PAY.getValue());
        mbrH5OrderMapper.update(mbrH5Order);

        // 插入CRM数据
        CrmUserInfoVO crmUserInfoVo = JSONObject.parseObject(attach, CrmUserInfoVO.class);
        Result<CrmUserInfoVO> crmUserInfoVoResult = systemServiceClient.savePrimeCrmUserInfo(crmUserInfoVo);
        if (crmUserInfoVoResult.getResult().equals("fail")) {
            throw new CustomException(RESP_CODE_ENUM.SERVICE_ERROR);
        }
    }

    /**
     * 处理prime订单异步通知
     *
     * @param outTradeNo    商户单号
     * @param transactionId 交易单号
     * @param payDate       支付时间
     * @param attach        订单自定义参数
     */
    @Transactional
    @Override
    public void handleNotifyOfNoScOrder(String outTradeNo, String transactionId, Date payDate, String attach) {
        log.info("\r\n****************orderNo={}\r\ntransactionId={}\r\nattach={}", outTradeNo, transactionId, attach);
        // 查询订单
        MbrH5Order mbrH5Order = mbrH5OrderMapper.getByOrderNo(outTradeNo);
        if (mbrH5Order == null) {
            throw new CustomException(RESP_CODE_ENUM.NO_DATA);
        }

        // 判断订单状态是否未未支付状态
        Integer orderStatus = mbrH5Order.getOrderStatus();
        if (!orderStatus.equals(MbrH5Order.ORDER_STATUS_ENUM.PRE_PAY.getValue())) {
            return;
        }

        // 更新订单状态订单数据
        mbrH5Order.setTransactionNo(transactionId);
        mbrH5Order.setPayDate(payDate);
        mbrH5Order.setOrderStatus(MbrH5Order.ORDER_STATUS_ENUM.SUCCESS_PAY.getValue());
        mbrH5OrderMapper.update(mbrH5Order);

        // 插入CRM数据
        CrmUserInfoVO crmUserInfoVo = JSONObject.parseObject(attach, CrmUserInfoVO.class);
        Result<CrmUserInfoVO> crmUserInfoVoResult = systemServiceClient.saveNoSCCrmUserInfo(crmUserInfoVo);
        if (crmUserInfoVoResult.getResult().equals("fail")) {
            throw new CustomException(RESP_CODE_ENUM.SERVICE_ERROR);
        }
    }

}
